package com.lineage.server.timecontroller.npc;

import com.lineage.server.model.Instance.L1NpcInstance;
import com.lineage.server.thread.GeneralThreadPool;
import java.util.Iterator;
import java.util.Map;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledFuture;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class NpcSpawnBossTimer extends TimerTask {
  private static final Log _log = LogFactory.getLog(NpcSpawnBossTimer.class);
  
  private ScheduledFuture<?> _timer;
  
  public static final Map<L1NpcInstance, Long> MAP = new ConcurrentHashMap<>();
  
  public void start() {
    int timeMillis = 30000;
    this._timer = GeneralThreadPool.get().scheduleAtFixedRate(this, 30000L, 30000L);
  }
  
  public void run() {
    try {
      if (MAP.isEmpty())
        return; 
      Iterator<L1NpcInstance> iterator = MAP.keySet().iterator();
      while (iterator.hasNext()) {
        L1NpcInstance npc = iterator.next();
        Long time = MAP.get(npc);
        long t = time.longValue() - 60L;
        if (time.longValue() > 0L) {
          MAP.put(npc, Long.valueOf(t));
        } else {
          spawn(npc);
          MAP.remove(npc);
        } 
        Thread.sleep(50L);
      } 
    } catch (Exception e) {
      _log.error("NPC(BOSS)召唤时间时间轴异常重启", e);
      GeneralThreadPool.get().cancel(this._timer, false);
      NpcSpawnBossTimer bossTimer = new NpcSpawnBossTimer();
      bossTimer.start();
    } 
  }
  
  private static void spawn(L1NpcInstance npc) {
    try {
      npc.getSpawn().executeSpawnTask(npc.getSpawnNumber(), npc.getId());
    } catch (Exception e) {
      _log.error(e.getLocalizedMessage(), e);
    } 
  }
}
